package tankgame03;

import java.io.*;
import java.util.ArrayList;
import java.util.Vector;

/**
 * @author DCSGO
 * @version 1.0
 * 记录并与文件交互
 * 存储退出时敌方坦克的位置与方向
 */

@SuppressWarnings({"all"})
public class LastEnemyTanks {
    private static final String filePath = "src\\lastEnemyTankInfo.txt";

    public static ArrayList<Node> loadLastEnemyTanks() {
        ArrayList<Node> enemyTanks = new ArrayList<>();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(filePath));
            String enemyTankInfo = null;
            while ((enemyTankInfo = br.readLine()) != null) {
                String[] xyd = enemyTankInfo.split("\\.");
                enemyTanks.add(new Node(Integer.parseInt(xyd[0]),
                        Integer.parseInt(xyd[1]), Integer.parseInt(xyd[2])));
            }
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return enemyTanks;
    }

    public static void save(Vector<EnemyTank> enemyTanks) {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(filePath));
            for (int i = 0; i < enemyTanks.size(); i++) {
                EnemyTank enemyTank = enemyTanks.get(i);
                if (enemyTank.isLive) {
                    bw.write(enemyTank.getX() + "." + enemyTank.getY() + "." + enemyTank.getDirection());
                    bw.newLine();
                }
            }
        } catch (IOException e) {
            e.getStackTrace();
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
